package com.zerowidth.moc.web.auth;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.zerowidth.db.bean.AuthTokenBean;
import com.zerowidth.db.bean.UserBean;
import com.zerowidth.db.op.AuthTokenDB;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Date;

public class TokenHelper {

    //token 有效期 10年
    private static long YEAR_10 = 10 * 365 * 24 * 60 * 60 * 1000;

    public static JWTVerifier getVerifier(UserBean user) {
        if (user == null) {
            return null;
        }
        try {
            return JWT.require(Algorithm.HMAC256(user.user_id)).build();
        } catch (Exception e) {
            return null;
        }
    }

    public static String createToken(String user_id) {
        if (user_id == null) {
            return null;
        }

        Date start = new Date();
        long currentTime = System.currentTimeMillis() + YEAR_10;//10年有效时间
        Date end = new Date(currentTime);
        String token = "";

        try {
            token = JWT.create().withAudience(user_id)
                    .withIssuedAt(start)
                    .withExpiresAt(end)
                    .sign(Algorithm.HMAC256(user_id));
        } catch (Exception e) {

        }

        return token;
    }

    public static String getUserIdByToken() {
        return getUserIdByToken(getRequestToken());
    }

    public static String getUserIdByToken(String token) {
        AuthTokenBean authTokenBean = AuthTokenDB.findUserByToken(token);
        if (authTokenBean == null) {
            return null;
        }

        return authTokenBean.user_id;
    }

    public static String getRequestToken() {
        String token = getRequest().getHeader("authToken");// 从 http 请求头中取出 token
        return token;
    }

    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }

}